import { ref } from 'vue'
export default function useMiddleInteractive() {
  const currentShow = ref('cd') // 显示歌词或者图片的小白点样式
  const middleLStyle = ref(null) // cd图片Dom
  const middleRStyle = ref(null) // 歌词Dom

  const touch = {} // 保存开始触发的x位置
  let currentView = 'cd' // 初始值
  function onMiddleTouchStart(e) {
    touch.startX = e.touches[0].pageX // 刚开始的坐标
    touch.startY = e.touches[0].pageY // y坐标位置
    touch.directionLocked = ''
  }
  function onMiddleTouchMove(e) {
    const deltaX = e.touches[0].pageX - touch.startX // 移动过程的坐标
    const deltaY = e.touches[0].pageY - touch.startY

    const absDeltaX = Math.abs(deltaX) // 获取的有可能是小数改成绝对值 有可能是负值
    const absDeltaY = Math.abs(deltaY)

    if (!touch.directionLocked) { // 用户滑动是x轴还是y轴 滑动横向坐标滑动大于纵向坐标 就是正常操作
      touch.directionLocked = absDeltaX >= absDeltaY ? 'h' : 'v'
    }

    if (touch.directionLocked === 'v') { // 用户滑动y轴不做操作 方向锁
      console.log('y轴滑动不做操作')
      return
    }
    const left = currentView === 'cd' ? 0 : -window.innerWidth // 获取到他初始的x轴位置
    const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX)) // 获取到他滑动的位置
    touch.parcent = Math.abs(offsetWidth / window.innerWidth) // 算出偏移比例 偏移量/屏幕宽度

    if (currentView === 'cd') {
      if (touch.parcent > 0.2) { // 手机拖动超过百分之二十 改变下面白条class
        currentShow.value = 'lyric'
      } else {
        currentShow.value = 'cd'
      }
    } else { // 他在歌词页面的时候 手指拖动到了百分之八十 改变白条Class
      if (touch.parcent < 0.8) {
        currentShow.value = 'cd'
      } else {
        currentShow.value = 'lyric'
      }
    }

    middleLStyle.value = { // 修改透明度
      opacity: 1 - touch.parcent
    }
    middleRStyle.value = {
      transform: `translate3d(${offsetWidth}px, 0, 0)`
    }
  }
  function onMiddleTouchEnd(e) {
    let offsetWidth
    let opacity
    if (currentShow.value === 'cd') {
      currentView = 'cd'
      offsetWidth = 0
      opacity = 1
    } else {
      currentView = 'lyric'
      offsetWidth = -window.innerWidth
      opacity = 0
    }

    const duration = 300
    middleLStyle.value = {
      opacity,
      transitionDuration: `${duration}ms`
    }

    middleRStyle.value = {
      transform: `translate3d(${offsetWidth}px, 0, 0)`,
      transitionDuration: `${duration}ms`
    }
  }

  return {
    currentShow,
    middleLStyle,
    middleRStyle,
    onMiddleTouchStart,
    onMiddleTouchMove,
    onMiddleTouchEnd
  }
}
